import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '@kernelproxy/i18n';
import { useCart } from '../../contexts/CartContext';
import { ShoppingCart, Zap, Calendar, Database, TrendingDown } from 'lucide-react';

type BillingPeriod = 'month' | 'year';

interface TrafficTier {
  gb: number;
  label: string;
  labelCN: string;
}

// Available traffic tiers
const trafficTiers: TrafficTier[] = [
  { gb: 10, label: '10 GB', labelCN: '10 GB' },
  { gb: 20, label: '20 GB', labelCN: '20 GB' },
  { gb: 50, label: '50 GB', labelCN: '50 GB' },
  { gb: 100, label: '100 GB', labelCN: '100 GB' },
  { gb: 200, label: '200 GB', labelCN: '200 GB' },
  { gb: 500, label: '500 GB', labelCN: '500 GB' },
  { gb: 1000, label: '1 TB', labelCN: '1 TB' },
  { gb: 2000, label: '2 TB', labelCN: '2 TB' },
];

// Base pricing per GB (monthly)
const basePricePerGB = {
  month: 0.75, // $0.75/GB for monthly
  year: 0.625,  // $0.625/GB for yearly (discounted)
};

// Volume discount tiers based on traffic amount
const getDiscountRate = (gb: number): number => {
  if (gb >= 1000) return 0.70; // 30% off for 1TB+
  if (gb >= 500) return 0.75;  // 25% off for 500GB+
  if (gb >= 200) return 0.85;  // 15% off for 200GB+
  if (gb >= 100) return 0.90;  // 10% off for 100GB+
  if (gb >= 50) return 0.95;   // 5% off for 50GB+
  return 1.0; // No discount
};

const PurchaseDynamicResidential = () => {
  const { language } = useLanguage();
  const { addItem } = useCart();
  const navigate = useNavigate();
  
  // Create language-aware link helper
  const getLink = (path: string) => language === 'zh-CN' ? `/zh-CN${path}` : path;

  // State management
  const [trafficAmount, setTrafficAmount] = useState<number>(50);
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>('month');
  const [customTraffic, setCustomTraffic] = useState<string>('50');

  // Period labels
  const periodLabels = {
    month: language === 'zh-CN' ? '按月' : 'Monthly',
    year: language === 'zh-CN' ? '按年' : 'Yearly',
  };

  // Calculate total price
  const totalPrice = useMemo(() => {
    const basePrice = basePricePerGB[billingPeriod];
    const discountRate = getDiscountRate(trafficAmount);
    const monthlyPrice = basePrice * trafficAmount * discountRate;
    
    // If yearly, multiply by 12
    const finalPrice = billingPeriod === 'year' ? monthlyPrice * 12 : monthlyPrice;
    
    return finalPrice.toFixed(2);
  }, [billingPeriod, trafficAmount]);

  // Calculate unit price after discount
  const unitPrice = useMemo(() => {
    const basePrice = basePricePerGB[billingPeriod];
    const discountRate = getDiscountRate(trafficAmount);
    return (basePrice * discountRate).toFixed(3);
  }, [billingPeriod, trafficAmount]);

  // Calculate discount percentage
  const discountPercentage = useMemo(() => {
    const discountRate = getDiscountRate(trafficAmount);
    return ((1 - discountRate) * 100).toFixed(0);
  }, [trafficAmount]);

  // Add to cart handler
  const handleAddToCart = () => {
    const discountValue = parseFloat(discountPercentage) / 100;
    addItem({
      productType: 'dynamic-residential',
      traffic: trafficAmount,
      unitPrice: parseFloat(unitPrice),
      totalPrice: parseFloat(totalPrice),
      ...(discountValue > 0 && { discount: discountValue }),
    });
    navigate(getLink('/dashboard/cart'));
  };

  // Handle custom traffic input
  const handleCustomTrafficChange = (value: string) => {
    setCustomTraffic(value);
    const numValue = parseInt(value) || 0;
    if (numValue >= 1 && numValue <= 5000) {
      setTrafficAmount(numValue);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '动态住宅 IPv6 选购' : 'Dynamic Residential IPv6 Purchase'}
          </h1>
          <p className="text-lg text-gray-600 dark:text-gray-300">
            {language === 'zh-CN' 
              ? '选择您需要的流量套餐，享受灵活的按需计费'
              : 'Choose your traffic package and enjoy flexible pay-as-you-go pricing'}
          </p>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* Configuration Panel */}
          <div className="lg:col-span-2 space-y-6">
            {/* Billing Period Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center mb-4">
                <Calendar className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '选择计费周期' : 'Select Billing Period'}
                </h2>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {(Object.keys(periodLabels) as BillingPeriod[]).map((period) => (
                  <button
                    key={period}
                    onClick={() => setBillingPeriod(period)}
                    className={`p-4 rounded-lg border-2 transition-all ${
                      billingPeriod === period
                        ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30 dark:border-blue-400 text-gray-900 dark:text-white'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500 text-gray-700 dark:text-gray-200'
                    }`}
                  >
                    <div className="text-center">
                      <div className="text-lg font-medium mb-1">
                        {periodLabels[period]}
                      </div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        ${basePricePerGB[period].toFixed(3)}/GB
                      </div>
                      {period === 'year' && (
                        <div className="text-xs text-green-600 dark:text-green-400 mt-1">
                          {language === 'zh-CN' ? '节省 17%' : 'Save 17%'}
                        </div>
                      )}
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Traffic Amount Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                  <Database className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                  <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                    {language === 'zh-CN' ? '选择流量' : 'Select Traffic'}
                  </h2>
                </div>
                {parseInt(discountPercentage) > 0 && (
                  <div className="flex items-center text-green-600 dark:text-green-400">
                    <TrendingDown className="w-4 h-4 mr-1" />
                    <span className="text-sm font-semibold">
                      {discountPercentage}% {language === 'zh-CN' ? '折扣' : 'OFF'}
                    </span>
                  </div>
                )}
              </div>

              <div className="space-y-6">
                {/* Quick Select Traffic Tiers */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                    {language === 'zh-CN' ? '快速选择' : 'Quick Select'}
                  </label>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    {trafficTiers.map((tier) => (
                      <button
                        key={tier.gb}
                        onClick={() => {
                          setTrafficAmount(tier.gb);
                          setCustomTraffic(tier.gb.toString());
                        }}
                        className={`py-3 px-4 rounded-lg text-sm font-medium transition-all ${
                          trafficAmount === tier.gb
                            ? 'bg-blue-600 text-white shadow-lg'
                            : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                        }`}
                      >
                        {language === 'zh-CN' ? tier.labelCN : tier.label}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Custom Traffic Input */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    {language === 'zh-CN' ? '或输入自定义流量 (GB)' : 'Or Enter Custom Traffic (GB)'}
                  </label>
                  <div className="flex items-center space-x-4">
                    <input
                      type="number"
                      min="1"
                      max="5000"
                      value={customTraffic}
                      onChange={(e) => handleCustomTrafficChange(e.target.value)}
                      className="flex-1 px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      placeholder={language === 'zh-CN' ? '输入流量 (1-5000 GB)' : 'Enter traffic (1-5000 GB)'}
                    />
                    <span className="text-gray-600 dark:text-gray-400 font-medium">GB</span>
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                    {language === 'zh-CN' ? '可输入 1-5000 GB 之间的任意值' : 'You can enter any value between 1-5000 GB'}
                  </p>
                </div>

                {/* Slider */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    {language === 'zh-CN' ? '滑动选择' : 'Slider Selection'}
                  </label>
                  <input
                    type="range"
                    min="1"
                    max="1000"
                    value={trafficAmount > 1000 ? 1000 : trafficAmount}
                    onChange={(e) => {
                      const val = parseInt(e.target.value);
                      setTrafficAmount(val);
                      setCustomTraffic(val.toString());
                    }}
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 accent-blue-600"
                  />
                  <div className="flex justify-between text-xs text-gray-600 dark:text-gray-400 mt-1">
                    <span>1 GB</span>
                    <span>500 GB</span>
                    <span>1000 GB</span>
                  </div>
                </div>

                {/* Discount Info */}
                <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 text-sm">
                  <div className="flex items-start">
                    <Zap className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2 mt-0.5 flex-shrink-0" />
                    <div>
                      <div className="text-blue-800 dark:text-blue-300 font-medium mb-2">
                        {language === 'zh-CN' ? '流量折扣阶梯：' : 'Volume Discounts:'}
                      </div>
                      <ul className="space-y-1 text-blue-700 dark:text-blue-400">
                        <li>• 50-99 GB: 5% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                        <li>• 100-199 GB: 10% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                        <li>• 200-499 GB: 15% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                        <li>• 500-999 GB: 25% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                        <li>• 1000+ GB: 30% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Features Info */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                {language === 'zh-CN' ? '套餐包含' : 'Package Includes'}
              </h3>
              <div className="grid md:grid-cols-2 gap-4 text-sm text-gray-700 dark:text-gray-300">
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '全球200+国家和地区' : 'Global 200+ countries and regions'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '真实住宅IP，高匿名' : 'Real residential IPs, high anonymity'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? 'HTTP/HTTPS/SOCKS5协议' : 'HTTP/HTTPS/SOCKS5 protocols'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '无限并发连接' : 'Unlimited concurrent connections'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '自动IP轮换' : 'Automatic IP rotation'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '24/7技术支持' : '24/7 technical support'}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Order Summary - Sticky Sidebar */}
          <div className="lg:col-span-1">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 sticky top-20 border-2 border-gray-200 dark:border-[#00d4ff]/30">
              <div className="flex items-center mb-6">
                <ShoppingCart className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '订单摘要' : 'Order Summary'}
                </h2>
              </div>

              <div className="space-y-4 mb-6">
                {/* Product */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '产品' : 'Product'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {language === 'zh-CN' ? '动态住宅 IPv6' : 'Dynamic Residential IPv6'}
                  </span>
                </div>

                {/* Traffic */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '流量' : 'Traffic'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {trafficAmount >= 1000 
                      ? `${(trafficAmount / 1000).toFixed(1)} TB`
                      : `${trafficAmount} GB`}
                  </span>
                </div>

                {/* Billing Period */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '计费周期' : 'Billing Period'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {periodLabels[billingPeriod]}
                  </span>
                </div>

                {/* Unit Price */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '单价' : 'Unit Price'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    ${unitPrice}/GB
                  </span>
                </div>

                {/* Discount */}
                {parseInt(discountPercentage) > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600 dark:text-gray-400">
                      {language === 'zh-CN' ? '折扣' : 'Discount'}:
                    </span>
                    <span className="font-medium text-green-600 dark:text-green-400">
                      -{discountPercentage}%
                    </span>
                  </div>
                )}

                <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                  <div className="flex justify-between items-center">
                    <span className="text-lg font-semibold text-gray-900 dark:text-white">
                      {language === 'zh-CN' ? '总计' : 'Total'}:
                    </span>
                    <span className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                      ${totalPrice}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400 text-right mt-1">
                    {language === 'zh-CN' 
                      ? `每${billingPeriod === 'month' ? '月' : '年'}` 
                      : `per ${billingPeriod}`}
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="space-y-3">
                <button
                  className="w-full bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-medium py-3 px-6 rounded-lg transition-all duration-200"
                  onClick={handleAddToCart}
                >
                  <span className="flex items-center justify-center gap-2">
                    <ShoppingCart size={20} />
                    {language === 'zh-CN' ? '加入购物车' : 'Add to Cart'}
                  </span>
                </button>

                <button
                  className="w-full border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 font-medium py-3 px-6 rounded-lg transition-all duration-200"
                  onClick={() => window.location.href = getLink('/pricing/dynamic-residential-ipv6')}
                >
                  {language === 'zh-CN' ? '返回定价页' : 'Back to Pricing'}
                </button>
              </div>

              {/* Additional Info */}
              <div className="mt-6 text-xs text-gray-500 dark:text-gray-400 space-y-2">
                <p>
                  {language === 'zh-CN' 
                    ? '• 支持多种支付方式'
                    : '• Multiple payment methods supported'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 即时开通，无需等待'
                    : '• Instant activation, no waiting'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 流量永久有效，不过期'
                    : '• Traffic never expires'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 7天退款保证'
                    : '• 7-day money-back guarantee'}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PurchaseDynamicResidential;
